package com.ouyunc.gateway.config.swagger;

import org.springframework.cloud.gateway.config.GatewayProperties;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author fangzhenxun
 * @Description: gateway swagger2 的集成，处理微服务集中处理
 * @Version V1.0
 **/
@Primary
@Profile({"dev", "test", "default"})
@Component("swagger2Config")
public class Swagger2Config implements SwaggerResourcesProvider {


    @Resource
    private GatewayProperties gatewayProperties;


    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> swaggerResources = new ArrayList<>();
        // 获取所有路由信息
        gatewayProperties.getRoutes().forEach(routeDefinition -> {
            swaggerResources.add(getSwaggerResources((String) routeDefinition.getMetadata().getOrDefault("routeName", routeDefinition.getId()), routeDefinition.getId()));
        });
        return swaggerResources;
    }

    private SwaggerResource getSwaggerResources(String name, String serviceId) {
        SwaggerResource resource = new SwaggerResource();
        resource.setName(name);
        resource.setLocation(serviceId + "/v3/api-docs");
        resource.setSwaggerVersion("3.0");
        return resource;
    }
}
